﻿function TestFlow() {
    var submitComplete = function (complete, err, result) {
        if (typeof (complete) == "function")
            complete(err, result);
        closeLoading();
        if (err) {
            showAlert('处理失败：' + err);
        } else {
            showAlert('处理完成');
        }
    }

    var backComplete = function (complete, err, result) {
        if (typeof (complete) == "function")
            complete(err, result);
        closeLoading();
        if (err) {
            showAlert('退回失败：' + err);
        } else {
            showAlert('退回完成');
        }
    }

    var toArray = function (parms) {
        var arr = [];
        if (!Array.isArray(parms)) {
            arr.push(parms);
            return arr;
        }
        return parms;
    }

    //任务下发
    //调用接口
    this.callTaskWait = function (parm, complete, success, fail) {
        callApi("/TestFlow/TaskWait", parm, complete, success, fail);
    }
    this.callTaskWaitBack = function (parm, complete, success, fail) {
        callApi("/TestFlow/TaskWaitBack", parm, complete, success, fail);
    }

    this.taskWait = function (parms, complete) {
        var self = this;
        parms = toArray(parms);
        confirm("是否下发任务？", ['是', '否'], function (e) {
            waterfall(null, parms,
                function (args, i, parms, callback) {
                    showLoading("正在下发(" + (i + 1) + "/" + parms.length + ")");
                    callApi("/TestFlow/TaskWait", parms[i], null,
                        function () {
                            callback(null, args, i + 1, parms)
                        },
                        function (msg) {
                            callback(msg, args, i + 1, parms)
                        });
                },
                function (err, result) {
                    submitComplete(complete, err, result);
                }
            );
        });
    }
    //this.taskWaitBack = function (parms, complete) {
    //    var self = this;
    //    parms = toArray(parms);
    //    mui.prompt('退回意见', '', '任务退回', ['确定', '取消'], function (e) {
    //        if (e.index == 0) {
    //            waterfall(e.value, parms,
    //                function (comment, i, parms, callback) {
    //                    showLoading("正在退回(" + (i + 1) + "/" + parms.length + ")：" + parms[i]);
    //                    callApi("/TestFlow/TaskBack", { nums: parms[i], comment: comment }, null,
    //                        function () { callback(null, comment, i + 1, parms) },
    //                        function (msg) { callback(msg, comment, i + 1, parms) });
    //                }, function (err, result) { backComplete(complete, err, result); }
    //            );
    //        }
    //    });
    //}

    this.taskConfirm = function (parms, complete) {
        parms = toArray(parms);
        var self = this;
        confirm("是否确认任务？", ['是', '否'], function (e) {
            waterfall(null, parms,
                function (args, i, parms, callback) {
                    showLoading("正在确认(" + (i + 1) + "/" + parms.length + ")：" + parms[i]);
                    callApi("/TestFlow/Confirm", {
                        nums: parms[i]
                    }, null,
                        function () {
                            callback(null, args, i + 1, parms)
                        },
                        function (msg) {
                            callback(msg, args, i + 1, parms)
                        });
                },
                function (err, result) {
                    submitComplete(complete, err, result);
                }
            );
        });
    }
    this.taskConfirmBack = function (parms, complete) {
        parms = toArray(parms);
        var self = this;
        mui.prompt('退回意见', '', '任务退回', ['确定', '取消'], function (e) {
            if (e.index == 0) {
                waterfall(e.value, parms,
                    function (comment, i, parms, callback) {
                        showLoading("正在退回(" + (i + 1) + "/" + parms.length + ")：" + parms[i]);
                        callApi("/TestFlow/TaskBack", {
                            nums: parms[i],
                            comment: comment
                        }, null,
                            function () {
                                callback(null, comment, i + 1, parms)
                            },
                            function (msg) {
                                callback(msg, comment, i + 1, parms)
                            });
                        //self.callTaskConfirmBack({ nums: parms[i], comment: comment }, null,
                        //    function () { callback(null, comment, i + 1, parms) },
                        //    function (msg) { callback(msg, comment, i + 1, parms) }
                        //);
                    },
                    function (err, result) {
                        backComplete(complete, err, result);
                    }
                );
            }
        });
    }
    //END - 任务确认

    //报告审核审批

    this.reportCheck = function (parms, complete) {
        parms = toArray(parms);
        var self = this;
        //debug(JSON.stringify(parms[0])); return;
        confirm("是否通过？", ['是', '否'], function (e) {
            waterfall(null, parms,
                function (args, i, parms, callback) {
                    var parm = parms[i];
                    showLoading("正在处理(" + (i + 1) + "/" + parms.length + ")：" + parm.reportnum);
                    callApi("/TestFlow/ReportCheck", parm, complete,
                        function () {
                            callback(null, args, i + 1, parms)
                        },
                        function (msg) {
                            callback(msg, args, i + 1, parms)
                        });
                },
                function (err, result) {
                    submitComplete(complete, err, result);
                }
            );
        });
    }

    this.reportCheckBack = function (parms, title, complete) {
        parms = toArray(parms);
        var self = this;
        mui.prompt('请输入退回意见', '', title + '退回', ['确定', '取消'], function (e) {
            if (e.index == 0) {
                var comment = e.value == null ? "" : e.value; //意见
                waterfall(comment, parms,
                    function (comment, i, parms, callback) {
                        var parm = parms[i];
                        showLoading("正在退回(" + (i + 1) + "/" + parms.length + ")：" + parm.reportnum);
                        parm.note = comment;
                        callApi("/TestFlow/ReportCheckBack", parm, complete,
                            function () {
                                callback(null, comment, i + 1, parms)
                            },
                            function (msg) {
                                callback(msg, comment, i + 1, parms)
                            });
                    },
                    function (err, result) {
                        backComplete(complete, err, result);
                    }
                );
            }
        });
    }

    //END -- 报告审核审批
};

function WorkFlow() {
    var flowAction = function (type, title) {
        if (type == "save")
            showLoading('正在' + title + '...');
        else
            showLoading('正在' + title + '...');
        axios.post("/WorkFlow/FlowAction?type=" + type, $('#form1').serialize(), {
            headers: {
                'Content-Type': 'application/x-www-form-urlencoded; charset=UTF-8'
            }
        }).then(function (r) {
            closeLoading();
            var data = r.data;
            if (data.code == 0) {
                if (type == "save") {
                    var isNew = $('#_P_Value').val().length == 0;
                    $('#_P_Value').val(data.data.instanceid);
                    $('#__taskid__').val(data.data.taskid);
                    $('#__groupid__').val(data.data.groupid);
                    showAlert2('保存成功');
                    if (isNew) {
                        window.location.href = data.data.url;
                    }
                } else {
                    showAlert2('处理成功', function () {
                        if (typeof (returnUrl2) != "undefined" && returnUrl2.length > 0) {
                            returnUrl2 = returnUrl2 + "&t=" + (new Date().getTime());
                            console.log(returnUrl2);
                            window.location.href = returnUrl2;
                        } else {
                            window.history.back();
                        }
                    });
                }
            } else {
                showAlert2('处理失败');
            }
        });
    }

    function filterSelectRange(selectRange, data) {
        var rangeItems = [] ;
        for (var i = 0; i < data.length; i++) {
            //dc56eee6-05ad-4de1-a340-0366f3e9bf95
            var item = data[i];
            var id = item.value;
            //for (var j = 0; j < defaultItems.length; j++) {
            //    var defaultId = defaultItems[j];
            //    if (id.indexOf(defaultId) >= 0) {
            //        rangeItems.push(item);
            //    }
            //}

            if (id.indexOf(selectRange) >= 0) {
                rangeItems.push(item);
            } else {
                if (item.type == 10 || item.type == 11 || item.type == 12) {
                    rangeItems.push(item);
                }
            }
            //var children = item["children"]; //TODO：以后再处理子部门选择范围
            //if (typeof (children) != "undefined" && children.length > 0) {
            //    var result = filterSelectRange(selectRange, children)
            //    for (var j = 0; j < result.length; j++) {
            //        item.children.push(result[j]);
            //    }
            //}
        }
        return rangeItems;
    }

    var showMemeberSelectDialog = function (data, t, stepInfo) {
        var selectValues = $("#__member__").val();
        var runSelect = stepInfo.runSelect;
        var handlerType = stepInfo.handlerType;
        var selectRange = stepInfo.selectRange;  //选择范围
        var defaultHandler = stepInfo.defaultHandler;  //默认处理者
        var backModel = stepInfo.backModel;
        var items = selectValues == "" ? [] : selectValues.split(',');
        if (t == "1") //只能选择部门
            submitMemberSelect.onlyDept(true);
        var defaultItems = defaultHandler == "" ? [] : defaultHandler.split(',');
        if (items.length == 0) { //没有选择人员时
            items = defaultItems;//如果设置了默认处理者，自动选择默认处理者
        }
        if (selectRange.length > 0) { //过滤选择范围
            data = filterSelectRange(selectRange, data);
        }
        console.dir(data);
        submitMemberSelect.show(data, items, function (r) {
            $("#__member__").val(r.value);
            confirm("是否提交？", ['是', '否'], function (e) {
                flowAction("submit", "提交");
            });
        });
    };

    var showMemberPicker = function (data, htval) {
        var layerType = 1;
        for (var i = 0; i < data.length; i++) { //自动计算层级
            var item = data[i];
            var children = item["children"];
            if (typeof (children) != "undefined" && children.length > 0) {
                layerType = 2;
                for (var j = 0; j < children.length; j++) {
                    var item2 = children[j];
                    var children2 = item2["children"];
                    if (typeof (children2) != "undefined" && children2.length > 0) {
                        layerType = 3;
                        break;
                    }
                }
                break;
            }
        }
        var cityPicker3 = new mui.PopPicker({
            layer: layerType //(hts.indexOf(htval.toString()) >= 0 ? 1 : (htval == "1" ? 2 : 3))
        });
        console.dir(data);
        cityPicker3.setData(data);
        cityPicker3.show(function (items) {
            var max = items.length;
            for (var i = max - 1; i >= 0; i--) {
                if (items[i]['text'] !== undefined) {
                    if (handlerType == "4") {
                        if (items[i]['value'].indexOf("d_") >= 0) {
                            mui.toast('不能选择部门!');
                            return;
                        }
                    }
                    $("#__member__").val(items[i]["value"]);
                    break;
                }
            }
            flowAction("submit", "提交");
        });
    }

    this.save = function () {
        flowAction("save", "保存");
    }

    this.back = function (e) {
        var btnArray = ['是', '否'];
        confirm('确认退回？', btnArray, function (e) {
            flowAction("back", "退回");
        });
    }

    this.submit = function (e) {

        if (nextstep.length > 1) { //有多个步骤
            cityPicker1.setData(nextstep);
            cityPicker1.show(function (items) {
                cityPicker1.hide(function (e) { });
                if (items[0]['text'] != "") {
                    stepid = items[0]['value'];
                    $("#__nextstep__").val(stepid)
                    $.each(stepusers, function (i, v) {
                        var vid = v.value;
                        var htval = "0";
                        if (vid == stepid) {
                            var stepInfo = stepinfos[0].Value;
                            $.each(stepinfos, function (i, v1) {
                                if (v1.Key == vid) {
                                    htval = v1.Value.handlerType;
                                    stepInfo = v1.Value;
                                }
                            });
                            showMemeberSelectDialog(v.children, htval, stepInfo);
                        }
                    });
                }
            }, false);

        } else {
            var stepInfo = stepinfos[0].Value;
            showMemeberSelectDialog(stepusers[0].children, handlerType, stepInfo);
        }
    }

    this.complete = function () {
        var btnArray = ['是', '否'];
        confirm('确认完成流程？', btnArray, function (e) {
            flowAction("complete", "完成");
        });
    }
}